package com.njwb.day17.maipiao;

public class SellTicket implements Runnable {
    private Ticket ticket;

    public SellTicket(Ticket ticket) {
        this.ticket = ticket;
    }

    @Override
    public void run() {
        while (true) {
            boolean sold = false;
            // 调用线程安全的卖票方法
            synchronized (ticket) {
                sold = ticket.sellOne();
                if (sold) {
                    System.out.println(Thread.currentThread().getName() + " 卖出一张票，还剩 " + ticket.getCount() + " 张");
                } else {
                    System.out.println(Thread.currentThread().getName() + " 发现票已售完");
                    break;
                }
            }

            if (sold) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
